<?php
session_start();
include_once("d:/shante/myzhuaqu.php");
require_once('d:/shante/vendor/autoload.php');
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverJavascriptExecutor;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverWait;
use Facebook\WebDriver\Interactions\WebDriverActions;
use Facebook\WebDriver\Cookie;
use Facebook\WebDriver\Remote\RemoteWebElement;
use Facebook\WebDriver\ExpectedConditions;


//$cookiestr=getDouyinCookie();
global $driver;
if($_REQUEST['cookie']!=""){
    $cookiestr=$_REQUEST['cookie']=trim(preg_replace("/cookie:\s*/i","",$_REQUEST['cookie']));
    file_put_contents("d:/wwwroot/www/shop/yunshop/cookie/weixin.txt",$_REQUEST['cookie']);
}
$url = $_REQUEST['url'];




gotoWeixinNewGoods();

function gotoWeixinNewGoods(){
    global $driver,$argv;

    $_SESSION['item_id']=$argv[1];
    //加载数据
    $json=file_get_contents("https://shop.shante.me/yunshop/getdata.php?item_id={$_SESSION['item_id']}&json=true&t=".time());
    $data=json_decode($json,1);
    $nn=explode(">",$data["category3"]);

    //关闭多移窗口
//    $output = array();
//    $return_var = 0;
//    exec('tasklist | findstr "chrome.exe"', $output, $return_var);
//    if ($return_var === 0) {
//        foreach ($output as $line) {
//            echo $line . PHP_EOL;
//            if (preg_match('/^chrome.exe\s*(\d+)\s+.*/', $line, $matches)) {
//                $pid = $matches[1];
//                $command = "taskkill /F /PID $pid"; // /F 表示强制终止进程
//                exec($command, $output, $return_var);
//            }
//        }
//    } else {
//        echo "Error executing command: " . $return_var . PHP_EOL;
//    }

    $options = new ChromeOptions();
    //$options->addArguments(['--headless']);  //不出现浏览器
    $options->addArguments(['--disable-blink-features=AutomationControlled']);
    $options->addArguments(['--disable-extensions']);
    $options->addArguments(['--disable-gpu']);
    $options->addArguments(['--disable-infobars']);
    $options->addArguments(['--disable-notifications']);
    $options->addArguments(['--disable-popup-blocking']);
    $options->addArguments(['--disable-web-security']);
    $options->addArguments(['--ignore-certificate-errors']);
    $options->addArguments(['--disable-site-isolation-trials']);
    $options->addArguments(['--disable-popup-blocking']);
    $options->addArguments(['--disable-blink-features=AutomationControlled']);
    $options->addArguments(['--disable-features=IsolateOrigins,site-per-process']);
    $options->addArguments(['--allow-file-access-from-files']);
    //$options->addArguments(['--remote-debugging-port=9222']);
    //$options->addArguments(['--auto-open-devtools-for-tabs']);
    $options->addArguments(['--no-sandbox']);
    $options->setExperimentalOption("useAutomationExtension", false);
    $options->setExperimentalOption("excludeSwitches", ['enable-automation']);
    $options->setExperimentalOption('prefs', [
     'profile.default_content_settings.popups' => 0,
     'download.default_directory' => '/d/temp',
     ]);
    $options->addArguments(['--user-data-dir=/d/temp']);

    if ($driver !== null) {
        $driver->quit();
        $driver = null;
    }

    $capabilities = DesiredCapabilities::chrome();
    $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
    $driver = RemoteWebDriver::create('http://localhost:9515', $capabilities);

//    $profile = new FirefoxProfile();
//    $profile->setPreference('browser.download.folderList', 2);
//    $profile->setPreference('browser.download.manager.showWhenStarting', false);
//    $profile->setPreference('browser.download.dir', __DIR__.'/temp');
//    $profile->setPreference('browser.helperApps.neverAsk.saveToDisk', 'application/pdf');
//    $capabilities = DesiredCapabilities::firefox();
//    $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
//    $driver = RemoteWebDriver::create('http://127.0.0.1:4444/wd/hub', $capabilities);

    $driver->executeScript("window.resizeTo(screen.availWidth, screen.availHeight);");
    $url="https://channels.weixin.qq.com/shop/goods/category?item_id={$_SESSION['item_id']}";
    $driver->get($url);
    $wait = new WebDriverWait($driver, 60);
    try {
        $wait = new WebDriverWait($driver, 5);
        $element = $wait->until(
            WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::cssSelector('.msg_content'))
        );
        $cookieString = file_get_contents("d:/wwwroot/www/shop/yunshop/cookie/weixin.txt");
        $cookies = explode(';', $cookieString);
        foreach ($cookies as $cookie) {
            list($name, $value) = explode('=', $cookie, 2);
            if ($name != null && trim($name) != "") {
                $cookieObj = new Cookie(trim($name), trim($value));
                $driver->manage()->addCookie($cookieObj);
            }
        }
        $driver->get("https://channels.weixin.qq.com/shop");
        $wait = new WebDriverWait($driver, 60);
        $wait->until(
            function ($driver) {
                $currentUrl = $driver->getCurrentUrl();
                return strpos($currentUrl, 'shop/home') !== false;
            }
        );
        $cookies = $driver->manage()->getCookies();
        $cookiestr = "";
        for ($i = 0; $i < count($cookies); $i++) {
            $cookiestr .= $cookies[$i]->getName() . "=" . $cookies[$i]->getValue() . ";";
        }
        file_put_contents("d:/wwwroot/www/shop/yunshop/cookie/weixin.txt", $cookiestr);
        $driver->get("https://channels.weixin.qq.com/shop/goods/category?item_id={$_SESSION['item_id']}");
    }catch (Exception $e){

    }
    $cookies = $driver->manage()->getCookies();
    $cookiestr = "";
    for ($i = 0; $i < count($cookies); $i++) {
        $cookiestr .= $cookies[$i]->getName() . "=" . $cookies[$i]->getValue() . ";";
    }

    function isShadowElementPresent($driver, $shadowHostSelector, $shadowSelector) {
        $shadowHost = $driver->findElement(WebDriverBy::cssSelector($shadowHostSelector));
        $jsExecutor = $driver->getExecuteScript();
        $shadowRoot = $jsExecutor->executeScript('return arguments[0].shadowRoot', [$shadowHost]);
        return $shadowRoot->findElement(WebDriverBy::cssSelector($shadowSelector)) !== null;
    }
    $shadowHostSelector = "#app > div > div.app_content > div:nth-child(4) > micro-app";


    $script=<<<TEXT
// 辅助函数：检查一个元素是否包含指定的文本  
function containsText(element, text) {  
    return element.textContent.trim().includes(text);  
}  
  
// 辅助函数：模拟点击事件  
function simulateClick(element) {  
    var event = new MouseEvent('click', {  
        'view': window,  
        'bubbles': true,  
        'cancelable': true  
    });  
    element.dispatchEvent(event);  
}  
  
// 等待一段时间的函数  
function wait(ms) {  
    return new Promise(resolve => setTimeout(resolve, ms));  
}  
  
// 主逻辑  
async function performActions() {  
    try {  
        // 查找第一个shadow DOM中的元素  
        var shadowRoot1 = document.querySelector("#app > div > div.app_content > div:nth-child(4) > micro-app").shadowRoot;  
        var selectList0 = shadowRoot1.querySelector("#selectList0");  
        var selectItems0 = selectList0.querySelectorAll("div.select_item");  
        for (var item of selectItems0) {  
            if (containsText(item, '{$nn[0]}')) {  
                simulateClick(item);  
                await wait(1000); // 等待1秒  
                break; // 找到并点击后跳出循环  
            }  
        }  
        
        var selectList1 = shadowRoot1.querySelector("#selectList1");  
        var selectItems1 = selectList1.querySelectorAll("div.select_item");  
        for (var item of selectItems1) {  
            if (containsText(item, '{$nn[1]}')) {  
                simulateClick(item);  
                await wait(2000); // 等待1秒  
                break; // 找到并点击后跳出循环  
            }  
        } 
        
        var selectList2 = shadowRoot1.querySelector("#selectList2");  
        var selectItems2 = selectList2.querySelectorAll("div.select_item");  
        for (var item of selectItems2) {  
            if (containsText(item, '{$nn[2]}')) {  
                simulateClick(item);  
                await wait(1000); // 等待1秒  
                break; // 找到并点击后跳出循环  
            }  
        } 
        
        var selectList3 = shadowRoot1.querySelector("#selectList3");  
        var selectItems3 = selectList3.querySelectorAll("div.select_item");  
        for (var item of selectItems3) {  
            if (containsText(item, '{$nn[3]}')) {  
                simulateClick(item);  
                await wait(1000); // 等待1秒  
                break; // 找到并点击后跳出循环  
            }  
        } 
        document.querySelector("#app > div > div.app_content > div:nth-child(4) > micro-app").shadowRoot.querySelector("#app > div.flex.justify-center > div > button").click()
    } catch (error) {  
        console.error('An error occurred:', error);  
    }  
}  
  
// 执行主逻辑  
performActions();


TEXT;
    $shadowSelector="#selectList0 > div:nth-child(1) > div > div";
    $wait = new WebDriverWait($driver, 5);
    try {
        $wait->until(
            WebDriverExpectedCondition::custom(
                function () use ($driver, $shadowHostSelector, $shadowSelector) {
                    return isShadowElementPresent($driver, $shadowHostSelector, $shadowSelector);
                }
            )
        );
    } catch (Throwable $e) {
        // 元素在指定时间内未出现，处理异常
        echo "Element not found within the specified time.";
    }
    $driver->executeScript($script);
    sleep(7);

    //用闪特精灵执行一回
    $url="https://channels.weixin.qq.com/shop/goods/entry?item_id={$_SESSION['item_id']}";
    $data_post['cookies']=$cookiestr;
    $data_post['url']=$url;
    $data_post['s_url']="https://shop.shante.me/Shop/Item/edit/id/{$_SESSION['item_id']}.html";
    $data_post['item_id']=$_SESSION['item_id'];
    $json=curl_post_json("https://shante.me/public/chrome/index.php",json_encode($data_post));
    $data=json_decode($json,1);
    $temp=$data['marker'];
    $temp=preg_replace("/javascript\:\(function\(\)\{|\}\)\(\)\;\s*$/","",$temp);
    $driver->executeScript($temp);
    $data_post = [
        'url' => 'https://channels.weixin.qq.com/shop/goods/entry',
        's_url' => "https://shop.shante.me/Shop/Item/edit/id/{$_SESSION['item_id']}.html",
        'content' => ''
    ];
    $jsonData = json_encode($data_post);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://shop.shante.me/yunshop/au3/click.php?XDEBUG_SESSION_START=5432534");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($jsonData)
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
    $shadowSelector = "#props-editor > div:nth-child(1) > div.default_box.default-box_reset-bottom.goods_basic > div.box_content > div > form > div:nth-child(1) > div.flex-1.mr-\\[24px\\] > div.weui-desktop-form__control-group.weui-desktop-form__control-group_warn > div > div.weui-desktop-form__input-area.borderSize > span > input";
    $wait = new WebDriverWait($driver, 10000);
    try {
        $wait->until(
            WebDriverExpectedCondition::custom(
                function () use ($driver, $shadowHostSelector, $shadowSelector) {
                    return isShadowElementPresent($driver, $shadowHostSelector, $shadowSelector);
                }
            )
        );
    } catch (Throwable $e) {
        // 元素在指定时间内未出现，处理异常
        echo "Element not found within the specified time.";
    }
    $data3=array();
    $data3["images"]=$data["images"];
    $jsonData=json_encode($data3);
    $localurl = "http://localhost:3000/downloadimages";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $localurl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'sec-ch-ua: "Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
        'sec-ch-ua-platform: "Windows"',
        'sec-ch-ua-mobile: ?0',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Accept: */*',
        'Sec-Fetch-Site: cross-site',
        'Sec-Fetch-Mode: cors',
        'Sec-Fetch-Dest: empty',
        'Accept-Encoding: gzip, deflate, br',
        'Accept-Language: zh-CN,zh;q=0.9',
        'Content-Length: ' . strlen($jsonData)
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $content=curl_exec($ch);
    curl_close($ch);
    $script=file_get_contents('https://shop.shante.me/yunshop/au3/click.js');
    $driver->executeScript($script);
    //$driver->quit();
}

function h($elements) {
    global $driver;
    if(array_key_exists(0,$elements)){
        $outerHTMLs = [];
        foreach ($elements as $element) {
            $outerHTML = $driver->executeScript("return arguments[0].outerHTML;", [$element]);
            $outerHTMLs[] = $outerHTML;
        }
        return $outerHTMLs;
    }else {
        $outerHTML = $driver->executeScript("return arguments[0].outerHTML;", [$elements]);
        return $outerHTML;
    }
    return "";
}

function html($str){
    $str=str_replace('"','\"',$str);
    $str=preg_replace("/\n|\r/Uis",'',$str);
    return $str;
}

function gethtml($jspath){
    global $driver;
    //$jspath=str_replace('"','\"',$jspath);
    $content=$driver->executeScript("return {$jspath}.outerHTML");
    return $content;
}

function getjshtml($jsel){
    global $driver;
    $content=$driver->executeScript("return arguments[0].outerHTML", [$jsel]);
    return $content;
}
